import { createRouter, createWebHistory } from 'vue-router';
import generateRouter from "@/hooks/common/generateRouter";
import Login from "@/views/Login";
import {useStore} from "vuex";
import {ElMessage} from "element-plus";

const routes=[{
    path:'/login',
    name:'login',
    component:Login
}]

const dynamicRoute = await generateRouter()||[]


const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes:[...routes,...dynamicRoute],
});

router.beforeEach((to,from,next)=>{
    const staffInfo = JSON.parse(localStorage.getItem("staffInfo"))
    let store = useStore()
    if (staffInfo){
        generateRouter().then((routes)=>{
            routes.forEach(route=>{
                if (!router.hasRoute(route.routeName)){
                    router.addRoute(route)
                }
            })
            next()
            store.dispatch('addStaffInfo',staffInfo)
        }).catch(err=>{
            ElMessage.error(err)
            console.log(err)
        })
    }else {
        if (to.name !== 'login'){
            next({name:'login'})
        }else {
            next()
        }
    }
})


export default router;